package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZMajor;
import com.sec.etech.employeesync.mapper.OrgEmployeeZMajorMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class MajorConfigHandler implements ConfigTableHandler<OrgEmployeeZMajor> {

    @Resource
    private OrgEmployeeZMajorMapper majorMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZMajor major = getEntityByName(name);
        if (major == null) {
            major = new OrgEmployeeZMajor();
            major.setCode(generateNextCode());
            major.setName(name);
            major.setActive(1);
            insertEntity(major);
            log.info("新增专业配置:name={}", name);
        }
        return major.getMajorId();
    }

    @Override
    public OrgEmployeeZMajor getEntityByName(String name) {
        return majorMapper.selectOne(Wrappers.<OrgEmployeeZMajor>lambdaQuery()
                .eq(OrgEmployeeZMajor::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZMajor politics = majorMapper.selectOne(Wrappers.<OrgEmployeeZMajor>lambdaQuery()
                .orderByDesc(OrgEmployeeZMajor::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZMajor::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZMajor entity) {
        majorMapper.insert(entity);
    }
}
